package com.example.cadmin;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cadmin.ScheduledTasks.DynamicTaskService;
import com.example.cadmin.ScheduledTasks.Task;
import com.example.cadmin.entity.*;
import com.example.cadmin.mapper.SysParamsetMapper;
import com.example.cadmin.security.dto.JwtUserDto;
import com.example.cadmin.service.*;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * pad接口api
 */
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin // 解决跨域问题
public class padController {

    @Resource
    public ArchivesService archivesService;
    @Resource
    public HostService hostService;
    @Resource
    public BorrowingRecordsService borrowingRecordsService;
    @Resource
    public MyUserService myUserService;
    @Resource
    public com.example.cadmin.utils.Netty.sendCmd sendCmd;
    @Resource
    private DynamicTaskService dynamicTask;
    @Resource
    public SysParamsetService sysParamsetService;

    /**
     * 测试网络连接
     *
     * @return
     */
    @GetMapping("/testNetwork")
    public ResponseModel testNetwork() {
        log.info("testNetwork");
        return ResponseModel.success("testNetwork success");
    }

    /**
     * 获取文件列表
     *
     * @param searchData 搜索关键字
     * @param page       页码
     * @param limit      每页条数
     * @return
     */
    @GetMapping("/getArchiveList")
    public Map<String, Object> getRegion(@RequestParam(value = "searchData", required = false) String searchData,
                                         @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                         @RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {
        log.info("searchData:{},page:{},limit:{}", searchData, page, limit);
        IPage<Map<String, Object>> hostPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<Archives> queryWrapper = new QueryWrapper<Archives>();
        if (StrUtil.isNotEmpty(searchData)) {
            queryWrapper.like("file_name", searchData);
        }

        hostPage = archivesService.pageMaps(hostPage, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", hostPage.getTotal());
        map.put("data", hostPage.getRecords());
        log.info(DateFormat.getTime());
        return map;
    }

    /**
     * 计算led位置
     */
    public static int calculateLEDPosition(int layer, int colum) {
        int index = (layer - 1) * 24 + colum;
        return index;
    }

    /**
     * 取出文件
     *
     * @param data 文件id
     * @return
     */
    @PostMapping("/takeOutArchive")
    public ResponseModel getArchive(@RequestBody JSONObject data) throws InterruptedException {
        if (StrUtil.isEmpty(data.getStr("uuid"))) {
            return ResponseModel.fail("文件uuid不能为空");
        }
        List<Archives> archivesList = archivesService.list(new QueryWrapper<Archives>().eq("uuid", data.getStr("uuid")));
        for (Archives archivesFor : archivesList) {
            Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", archivesFor.getNumber()));
            //发送led打开命令
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("cmd", "led_open");
            map.put("cabinet_id", Convert.toInt(host.getNumber()));
            map.put("led_index", calculateLEDPosition(Convert.toInt(archivesFor.getCurrentLayer()), Convert.toInt(archivesFor.getCurrentColumn())));
            map.put("led_num", 1);
            String sendMap = JSONUtil.toJsonStr(map);
            sendCmd.send(sendMap, null, host.getIp());
            archivesFor.setStatus(1);
            archivesService.updateById(archivesFor);
            log.info(DateUtil.now() + " 取出档案成功");
            Thread.sleep(150);
        }
        //添加借阅记录
        Archives archives = archivesList.get(0);
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileName(archives.getFileName());
        MyUser user = myUserService.getById(archives.getUserId());
        borrowingRecords.setDeptId(user.getDeptId());
        borrowingRecords.setBorrowers("pda用户");
        borrowingRecords.setBorrowingDate(DateFormat.getTime());
        borrowingRecords.setPurpose("手持pda借阅");
        borrowingRecords.setEstimatedDate(DateFormat.getTime());
        borrowingRecords.setCreateTime(DateFormat.getTime());
        borrowingRecords.setDataStatus(1);
        borrowingRecords.setStatus(1);
        borrowingRecords.setNumber(archives.getNumber());
        boolean state = borrowingRecordsService.save(borrowingRecords);
        Task task = new Task();
        Date date = DateUtil.date();
        SysParamset sysParamset = sysParamsetService.getById(2);
        Date newDate = DateUtil.offset(date, DateField.SECOND, Convert.toInt(sysParamset.getParamValue()));
        LocalDateTime newDateTime = DateUtil.toLocalDateTime(newDate);
        task.setUuid(Convert.toStr(archives.getUuid()));
        task.setStart(newDateTime);
        dynamicTask.add(task);
        return state ? ResponseModel.success("取出档案名为  " + archives.getFileName() + "  成功") : ResponseModel.fail("取出档案提交失败");
    }

    /**
     * 归还文件
     *
     * @param data 文件id
     * @return
     */
    @PostMapping("/returnArchive")
    public ResponseModel returnArchive(@RequestBody JSONObject data) throws InterruptedException {
        if (StrUtil.isEmpty(data.getStr("uuid"))) {
            return ResponseModel.fail("文件uuid不能为空");
        }
        List<Archives> archivesList = archivesService.list(new QueryWrapper<Archives>().eq("uuid", data.getStr("uuid")));
        for (Archives archivesFor : archivesList) {
            Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", archivesFor.getNumber()));
            //发送led打开命令
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("cmd", "led_open");
            map.put("cabinet_id", Convert.toInt(host.getNumber()));
            map.put("led_index", calculateLEDPosition(Convert.toInt(archivesFor.getCurrentLayer()), Convert.toInt(archivesFor.getCurrentColumn())));
            map.put("led_num", 1);
            String sendMap = JSONUtil.toJsonStr(map);
            sendCmd.send(sendMap, null, host.getIp());
            archivesFor.setStatus(0);
            archivesService.updateById(archivesFor);
            log.info(DateUtil.now() + " 取出档案成功");
            Thread.sleep(150);
        }
        Archives archives = archivesList.get(0);
        //添加借阅记录
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileName(archives.getFileName());
        MyUser user = myUserService.getById(archives.getUserId());
        borrowingRecords.setDeptId(user.getDeptId());
        borrowingRecords.setBorrowers("pda用户");
        borrowingRecords.setBorrowingDate(DateFormat.getTime());
        borrowingRecords.setPurpose("手持pda归还");
        borrowingRecords.setCreateTime(DateFormat.getTime());
        borrowingRecords.setDataStatus(2);
        borrowingRecords.setStatus(1);//层 和 列
        borrowingRecords.setReturnLayerColumn(archives.getCurrentLayer() + "-" + archives.getCurrentColumn());
        borrowingRecords.setNumber(archives.getNumber());
        borrowingRecordsService.save(borrowingRecords);
        Task task = new Task();
        Date date = DateUtil.date();
        SysParamset sysParamset = sysParamsetService.getById(2);
        Date newDate = DateUtil.offset(date, DateField.SECOND, Convert.toInt(sysParamset.getParamValue()));
        LocalDateTime newDateTime = DateUtil.toLocalDateTime(newDate);
        task.setUuid(Convert.toStr(archives.getUuid()));
        task.setStart(newDateTime);
        dynamicTask.add(task);
        return ResponseModel.success("归还档案名  " + archives.getFileName() + "  成功");
    }

    /**
     * 日志列表
     *
     * @param searchData 搜索关键字
     * @param page       页码
     * @param limit      每页条数
     * @return
     */
    @GetMapping("/borrowingRecordsList")
    public Map<String, Object> borrowingRecordsList(@RequestParam(value = "searchData", required = false) String searchData,
                                                    @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                    @RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {
        log.info("searchData:{},page:{},limit:{}", searchData, page, limit);
        IPage<Map<String, Object>> borrowingRecordsPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<BorrowingRecords> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(searchData)) {
            queryWrapper.like("file_name", searchData);
        }
        queryWrapper.select("id", "file_name", "data_status", "create_time").orderByDesc("create_time");
        borrowingRecordsPage = borrowingRecordsService.pageMaps(borrowingRecordsPage, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", borrowingRecordsPage.getTotal());
        map.put("data", borrowingRecordsPage.getRecords());
        log.info(DateFormat.getTime());
        return map;
    }
}
